<template>
  <div class="login-page">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click="$route.go(-1)"
    />
    <span class="pp">欢迎注册</span>
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="用户名"
        placeholder="请输入手机号"
        :rules="[
          { required: true },
          { pattern: tel, message: '请输入正确手机号' }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="请填写密码"
        :rules="[
          { required: true },
          {
            validator: pwd,
            message: '密码由大于等于6位的字母数字组成,字母开头'
          }
        ]"
      />
      <van-field
        v-model="repassword"
        type="password"
        name="repassword"
        label="确认密码"
        placeholder="请再次确认密码"
        :rules="[
          { required: true },
          {
            validator: pwd,
            message: '密码由大于等于6位的字母数字组成,字母开头'
          },
          {
            validator: repwd,
            message: '密码应与之前一致'
          }
        ]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <router-link to="/login" class="login-link">已有账号，去登录</router-link>
  </div>
</template>

<script>
import { registerAPI } from '@/api/user'
export default {
  name: 'login-page',
  data () {
    return {
      mobile: '',
      password: '',
      repassword: '',
      tel: /^1\d{10}$/
    }
  },
  methods: {
    async onSubmit (values) {
      const data = await registerAPI(values)
      console.log(values)
      console.log(data)
      this.$toast.success(data.data.errmsg)
      localStorage.getItem('ydd-token', data.data.token)
      if (data.data.errno === 0) {
        this.$router.push('/login')
      }
    },
    pwd (val) {
      return /^[a-zA-Z]\w{5,}$/.test(val)
    },
    repwd (val) {
      return val === this.password
    }
  }
}
</script>

<style lang="less" scoped>
.pp {
  display: block;
  margin: 15px auto;
  color: #1989fa;
  font-size: 30px;
  text-align: center;
}
.login-link {
  float: right;
  padding-right: 20px;
  font-size: 12px;
}
</style>
